package com.example.weather_app.diary;

import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.weather_app.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class EditDiaryActivity extends AppCompatActivity {
    private EditText etTitle, etDate, etContent, etReminderTime;
    private Switch sbEnableReminder;
    private Button btnSave, btnCancel;
    private DiaryDao diaryDao;
    private String diaryId;
    private Diary diary;
    private SimpleDateFormat dateFormat, timeFormat;
    private Calendar reminderCalendar;
    private boolean isReminderSet = false;
    private String oldReminderTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_edit_diary);

        // 设置Toolbar
        androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("编辑日记");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        // 初始化组件
        etTitle = findViewById(R.id.etTitle);
        etDate = findViewById(R.id.etDate);
        etContent = findViewById(R.id.etContent);
        etReminderTime = findViewById(R.id.etReminderTime);
        sbEnableReminder = findViewById(R.id.sbEnableReminder);
        btnSave = findViewById(R.id.btnSave);
        btnCancel = findViewById(R.id.btnCancel);
        diaryDao = new DiaryDao(this);
        dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);
        reminderCalendar = Calendar.getInstance();

        // 获取日记ID
        if (getIntent() != null && getIntent().hasExtra("diaryId")) {
            diaryId = getIntent().getStringExtra("diaryId");
            loadDiary(diaryId);
        } else {
            finish();
        }

        // 日期选择器
        etDate.setOnClickListener(v -> showDatePicker());

        // 提醒时间选择器
        etReminderTime.setOnClickListener(v -> showTimePicker());

        // 启用提醒开关
        sbEnableReminder.setOnCheckedChangeListener((buttonView, isChecked) -> {
            isReminderSet = isChecked;
            etReminderTime.setEnabled(isChecked);
        });

        // 保存按钮点击事件
        btnSave.setOnClickListener(v -> updateDiary());

        // 取消按钮点击事件
        btnCancel.setOnClickListener(v -> finish());
    }

    // 加载日记数据
    private void loadDiary(String id) {
        diary = diaryDao.getDiaryById(id);
        if (diary != null) {
            etTitle.setText(diary.getTitle());
            etDate.setText(diary.getDate());
            etContent.setText(diary.getContent());

            // 处理提醒时间
            oldReminderTime = diary.getReminderTime();
            if (oldReminderTime != null && !oldReminderTime.isEmpty()) {
                sbEnableReminder.setChecked(true);
                isReminderSet = true;
                etReminderTime.setEnabled(true);
                etReminderTime.setText(oldReminderTime);

                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
                    Date reminderDate = sdf.parse(oldReminderTime);
                    reminderCalendar.setTime(reminderDate);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 显示日期选择器
    private void showDatePicker() {
        String[] dateParts = etDate.getText().toString().split("-");
        int year = Integer.parseInt(dateParts[0]);
        int month = Integer.parseInt(dateParts[1]) - 1;
        int day = Integer.parseInt(dateParts[2]);

        DatePickerDialog dialog = new DatePickerDialog(
                this,
                (view, year1, month1, dayOfMonth) -> {
                    String selectedDate = year1 + "-" + String.format("%02d", month1 + 1) + "-" + String.format("%02d", dayOfMonth);
                    etDate.setText(selectedDate);
                },
                year, month, day
        );
        dialog.show();
    }

    // 显示时间选择器
    private void showTimePicker() {
        if (diary != null && diary.getReminderTime() != null) {
            String[] timeParts = diary.getReminderTime().split(" ")[1].split(":");
            int hour = Integer.parseInt(timeParts[0]);
            int minute = Integer.parseInt(timeParts[1]);

            TimePickerDialog dialog = new TimePickerDialog(
                    this,
                    (view, hourOfDay, minute1) -> {
                        reminderCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                        reminderCalendar.set(Calendar.MINUTE, minute1);
                        reminderCalendar.set(Calendar.SECOND, 0);
                        String time = timeFormat.format(reminderCalendar.getTime());
                        etReminderTime.setText(etDate.getText().toString() + " " + time);
                    },
                    hour, minute, true
            );
            dialog.show();
        } else {
            Calendar calendar = Calendar.getInstance();
            TimePickerDialog dialog = new TimePickerDialog(
                    this,
                    (view, hourOfDay, minute) -> {
                        reminderCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                        reminderCalendar.set(Calendar.MINUTE, minute);
                        reminderCalendar.set(Calendar.SECOND, 0);
                        String time = timeFormat.format(reminderCalendar.getTime());
                        etReminderTime.setText(etDate.getText().toString() + " " + time);
                    },
                    calendar.get(Calendar.HOUR_OF_DAY),
                    calendar.get(Calendar.MINUTE),
                    true
            );
            dialog.show();
        }
    }

    // 更新日记
    private void updateDiary() {
        String title = etTitle.getText().toString().trim();
        String content = etContent.getText().toString().trim();
        String date = etDate.getText().toString().trim();

        if (title.isEmpty() && content.isEmpty()) {
            etTitle.setError("请输入标题或内容");
            return;
        }

        if (diary == null) {
            return;
        }

        // 取消旧提醒
        cancelOldReminder();

        // 设置新日记数据
        diary.setTitle(title);
        diary.setContent(content);
        diary.setDate(date);

        if (isReminderSet) {
            String reminderTime = etReminderTime.getText().toString().trim();
            if (!reminderTime.isEmpty()) {
                diary.setReminderTime(reminderTime);
                setReminder(this, diary.getId(), reminderTime);
            } else {
                diary.setReminderTime(null);
            }
        } else {
            diary.setReminderTime(null);
        }

        Log.d("EditDiaryActivity", "Updating diary with ID: " + diary.getId());
        int result = diaryDao.updateDiary(diary);
        if (result > 0) {
            Log.d("EditDiaryActivity", "Diary updated successfully: " + diary.getTitle());
            Intent intent = new Intent();
            setResult(RESULT_OK, intent);
            finish();
        } else {
            Log.d("EditDiaryActivity", "Failed to update diary: " + diary.getTitle());
            // 更新失败处理
        }
    }

    // 修正后的 setReminder 方法，添加精确闹钟权限检查
    private void setReminder(Context context, String diaryId, String reminderTime) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        Intent intent = new Intent(context, ReminderReceiver.class);
        intent.setAction("com.example.weather_app.ACTION_DIARY_REMINDER");
        intent.putExtra("diaryId", diaryId);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                context,
                diaryId.hashCode(),
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
        );

        // 解析提醒时间
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
            long triggerTime = sdf.parse(reminderTime).getTime();

            // 关键修改：检查精确闹钟权限 (Android 12+)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                if (!alarmManager.canScheduleExactAlarms()) {
                    // 没有权限，引导用户到设置页面
                    Log.w("DiaryApp", "没有精确闹钟权限，需要用户授权");

                    // 这里可以显示一个Toast或Dialog提示用户
                    Toast.makeText(context, "需要精确闹钟权限才能设置提醒", Toast.LENGTH_SHORT).show();

                    // 跳转到设置页面让用户授权
                    Intent settingsIntent = new Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM);
                    settingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(settingsIntent);
                    return;
                }
            }

            // 根据不同版本设置闹钟
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
            } else {
                alarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
            }

            Log.d("DiaryApp", "提醒已设置: " + reminderTime);

        } catch (Exception e) {
            Log.e("DiaryApp", "设置提醒失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 取消旧提醒
    private void cancelOldReminder() {
        if (oldReminderTime != null && !oldReminderTime.isEmpty()) {
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            Intent intent = new Intent(this, ReminderReceiver.class);
            intent.setAction("com.example.weather_app.ACTION_DIARY_REMINDER");
            intent.putExtra("diaryId", diaryId);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(
                    this,
                    diaryId.hashCode(),
                    intent,
                    PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
            );

            alarmManager.cancel(pendingIntent);
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }
}